import csv
import pandas as pd

# 从 txt 文件中读取数据
try:
    with open('数据.txt', 'r') as file:
        data = file.read()
except FileNotFoundError:
    print("错误: 未找到输入文件 '数据.txt'。")
else:
    # 分割每组数据
    groups = data.split('\n\n')

    extracted_data = []
    current_receiver_number = None

    for group in groups:
        lines = group.strip().split('\n')
        if not lines:
            continue

        for line in lines:
            parts = line.strip().split()
            
            # 检查是否是接收点编号行（形如 "1 25"）
            if len(parts) == 2 and parts[0].isdigit() and parts[1].isdigit():
                current_receiver_number = int(parts[0])
                continue
            
            # 检查是否是数据行（至少需要7个数据）
            if len(parts) >= 9 and current_receiver_number is not None:
                try:
                    path_number = int(parts[0])
                    received_power = float(parts[2])
                    vertical_aoa = float(parts[5])
                    horizontal_aoa = float(parts[6])
                    
                    extracted_data.append({
                        '接收点编号': current_receiver_number,
                        '路径编号': path_number,
                        '接收功率': received_power,
                        '垂直到达角': vertical_aoa,
                        '水平到达角': horizontal_aoa
                    })
                except (ValueError, IndexError):
                    continue

    try:
        # 将数据转换为DataFrame
        df = pd.DataFrame(extracted_data)
        
        # 保存为CSV文件
        df.to_csv('output.csv', index=False)
        print("数据已成功写入 'output.csv'。")
        
        # 保存为Excel文件
        df.to_excel('output.xlsx', index=False)
        print("数据已成功写入 'output.xlsx'。")
        
    except Exception as e:
        print(f"错误: 写入文件时出现问题: {e}")

    